import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:flutter_ahj_app/app/yhpc/YhpcViewModel.dart';
import 'package:flutter_ahj_app/base/basewidget/HttpUtils/HttpBaseConst.dart';
import 'package:flutter_ahj_app/base/basewidget/view/BaseWidget.dart';
import 'package:flutter_ahj_app/base/bean/FileUpLoadBean.dart';
import 'package:flutter_ahj_app/base/bean/flutter_AMapLocation_map.dart';
import 'package:flutter_ahj_app/base/utils/HttpUtils.dart';
import 'package:flutter_ahj_app/base/utils/JUIKit/JText.dart';
import 'package:flutter_ahj_app/base/utils/StringUtils.dart';
import 'package:flutter_ahj_app/base/utils/ToastUtils.dart';
import 'package:flutter_ahj_app/base/utils/date_util.dart';
import 'package:flutter_ahj_app/base/utils/image_picked.dart';
import 'package:flutter_ahj_app/base/utils/mTopBar.dart';
import 'package:flutter_ahj_app/base/utils/permission/PerUtils.dart';
import 'package:flutter_ahj_app/base/utils/permission/SelectPicUtils.dart';
import 'package:flutter_ahj_app/base/values/SQColor.dart';
import 'package:flutter_ahj_app/base/values/dimens.dart';
import 'package:flutter_ahj_app/base/utils/date_util.dart';
import '../../../base/utils/video_player_page.dart';
import 'package:permission_handler/permission_handler.dart';

class YhzlysView extends BaseStatefulWidget {
  final String id;
  YhzlysView({this.id});

  @override
  State<StatefulWidget> initState() {
    return YhzlysViewState();
  }
}

class YhzlysViewState extends BaseState<YhpcViewModel, YhzlysView> {

  TextEditingController _ysqksmCtr = TextEditingController(); // 验收情况说明
  String _selYhjg = 'pass';


  AMapLocation location;
  List<String> _imageUrls = [];

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
  }

  @override
  Widget initWidget() {
    return Scaffold(
      backgroundColor: Color(0xfff4f5f6),
      appBar: MTopBar(
        elevation: 0,
        title: '验收',
      ).create(),
      body: _bodyView(),
    );
  }

  _bodyView() {
    return Container(
      child: Column(
        children: [
          Expanded(
            child: Container(
              margin: EdgeInsets.all(15),
              decoration: BoxDecoration(
                  borderRadius: new BorderRadius.all(Radius.circular(6.0)),
                  color: SQColor.white),
              child: SingleChildScrollView(
                child: Column(
                  children: [
                    Container(
                      margin: EdgeInsets.fromLTRB(15, 15, 15, 0),
                      child: Column(
                        children: [
                          Container(
                            child: Row(
                              children: [
                                JText(
                                  '* ',
                                  color: SQColor.red,
                                ),
                                Container(
                                  child: JText('验收结果'),
                                ),
                              ],
                            ),
                          ),
                          Container(
                            margin: EdgeInsets.only(top: 10),
                            child: Row(
                              children: [
                                Expanded(
                                  child: InkWell(
                                    onTap: () {
                                      setState(() {
                                        _selYhjg = 'pass';
                                      });
                                    },
                                    child: Container(
                                      alignment: Alignment.center,
                                      margin: EdgeInsets.only(right: 5),
                                      height: 35,
                                      decoration: BoxDecoration(
                                          color: _selYhjg == 'pass'
                                              ? SQColor.theme_color
                                              : SQColor.white,
                                          border: Border.all(
                                            width: 1,
                                            color: SQColor.theme_color,
                                          ),
                                          borderRadius:
                                          BorderRadius.circular(8)),
                                      child: JText('通过',
                                          color: _selYhjg == 'pass'
                                              ? SQColor.white
                                              : SQColor.theme_color,
                                          fontSize: 14),
                                    ),
                                  ),
                                ),
                                Expanded(
                                  child: InkWell(
                                    onTap: () {
                                      setState(() {
                                        _selYhjg = 'reject';
                                      });
                                    },
                                    child: Container(
                                      alignment: Alignment.center,
                                      margin: EdgeInsets.only(right: 5),
                                      height: 35,
                                      decoration: BoxDecoration(
                                          color: _selYhjg == 'reject'
                                              ? SQColor.theme_color
                                              : SQColor.white,
                                          border: Border.all(
                                            width: 1,
                                            color: SQColor.theme_color,
                                          ),
                                          borderRadius:
                                          BorderRadius.circular(8)),
                                      child: JText('驳回',
                                          color: _selYhjg == 'reject'
                                              ? SQColor.white
                                              : SQColor.theme_color,
                                          fontSize: 14),
                                    ),
                                  ),
                                ),
                              ],
                            ),
                          ),
                        ],
                      ),
                    ),

                    _commField(
                      isMust:  _selYhjg == 'reject' ? true : false,
                      controller: _ysqksmCtr,
                      title: '验收情况说明',
                      hintText: '请输入验收情况说明',
                      maxLength: 500,
                    ),
                    Container(
                      margin: EdgeInsets.fromLTRB(15, 15, 15, 0),
                      child: Column(
                        children: [
                          Container(
                            child: Row(
                              children: [
                                Container(
                                  child: JText('验收附件'),
                                ),
                              ],
                            ),
                          ),
                          buildImagePicked(context, true),
                        ],
                      ),
                    ),
                    Container(
                      height: 20,
                    ),
                  ],
                ),
              ),
            ),
          ),
          _bottomView()
        ],
      ),
    );
  }
  int _maxCount = 6;
  Widget buildImagePicked(BuildContext context, bool isBefore) {
    return new Container(
        padding: const EdgeInsets.all(10.0),
        child: GridView.builder(
            padding: EdgeInsets.zero,
            physics: const NeverScrollableScrollPhysics(),
            shrinkWrap: true,
            gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                crossAxisCount: 4, //每行三列
                childAspectRatio: 1.0 //显示区域宽高相等
                ),
            itemCount: _imageUrls.length == 0
                ? 1
                : (_imageUrls.length == _maxCount
                ? _imageUrls.length
                : _imageUrls.length + 1),
            itemBuilder: (context, index) {
              return _item(index);
            }));
  }

  _item(int index) {
    List imgs = _imageUrls;
    return new GestureDetector(
      onTap: () {
        if (index != imgs.length) {
          if (imgs[index].contains("mp4")) {
            Navigator.push(
                context,
                MaterialPageRoute(
                    builder: (context) => VideoPlayerPage(
                          videoPath: imgs[index],
                          videoSource: "2",
                        )));
          } else {
            List<String> filePath = [];
            int position = 0;
            for (int i = 0; i < imgs.length; i++) {
              if (!imgs[i].contains(".mp4")) {
                filePath.add(imgs[i]);
              }
            }
            for (int i = 0; i < filePath.length; i++) {
              if (filePath[i] == imgs[index]) {
                position = i;
              }
            }
            Navigator.pushNamed(context, "/ShowImage",
                arguments: {'position': position, 'filePath': filePath});
          }
        } else {
          _pickImage();
        }
      },
      child: index != imgs.length
          ? Container(
              margin: EdgeInsets.only(right: 5, bottom: 5),
              child: ImagePicked(
                key: UniqueKey(),
                imageUrl: imgs[index],
                closeState: "0",
                index: index,
                boxFit: BoxFit.cover,
                valueChanged: (index) {
                  setState(() {
                    imgs.removeAt(index);
                  });
                },
              ),
            )
          : new Container(
              color: Theme.of(context).dividerColor,
              width: (MediaQuery.of(context).size.width - 32.0 - 8.0) / 4,
              height: (MediaQuery.of(context).size.width - 32.0 - 8.0) / 4,
              child: new Icon(
                Icons.add,
                size: 20.0,
                color: Colors.grey,
              ),
            ),
    );
  }

  bool showing = false;
  //多图选择器
  _pickImage() async {
    showing = true;
    showDialog<bool>(
      context: context,
      builder: (BuildContext context) {
        return new SimpleDialog(
          title: new Text('*选择附件(隐患视图)'),
          children: <Widget>[
            new SimpleDialogOption(
              child: new InkWell(
                child: new Container(
                  child: new Text(
                    '照相',
                    style: new TextStyle(fontSize: 16),
                  ),
                  height: 48,
                  alignment: Alignment.centerLeft,
                ),
              ),
              onPressed: () {
                onSelectPicClick("0");
                Navigator.of(context).pop(true);
                showing = false;
              },
            ),
            new SimpleDialogOption(
              child: new InkWell(
                child: new Container(
                  child: new Text(
                    '从相册选择',
                    style: new TextStyle(fontSize: 16),
                  ),
                  height: 48,
                  alignment: Alignment.centerLeft,
                ),
              ),
              onPressed: () {
                onSelectPicClick("1");
                Navigator.of(context).pop(true);
                showing = false;
              },
            ),
            new SimpleDialogOption(
              child: new InkWell(
                child: new Container(
                  child: new Text(
                    '视频录制',
                    style: new TextStyle(fontSize: 16),
                  ),
                  height: 48,
                  alignment: Alignment.centerLeft,
                ),
              ),
              onPressed: () {
                onSelectPicClick("2");
                Navigator.of(context).pop(true);
                showing = false;
              },
            ),
          ],
        );
      },
    );
  }

  void onSelectPicClick(String type) async {
    List imgs = _imageUrls;
    List result;
    Map<String, String> map = {
      "count": (_maxCount - imgs.length).toString(),
      "adress": location == null ? "暂无获取定位信息" : location.locationDescribe
    };
    if ("0" == type) {
      //照相
      if (location == null) {
        String resultStr =
        await PerUtils.checkPermission(context, [Permission.location]);
        if (resultStr == '1') {
          location = await FlutterAMapLocation.getCurrentLocation();
          if (location == null) {
            ToastUtils.showToast("获取位置信息失败，暂不能拍照");
          } else {
            map["adress"] = location.locationDescribe;
            String resultStr = await PerUtils.checkPermission(
                context, [Permission.camera]);
            if (resultStr == '1') {
              result = await SelectPicUtils.getTakePic(map);
            }
          }
        }else {
          ToastUtils.showToast("获取位置信息失败，暂不能拍照");
        }
      } else {
        String resultStr =
        await PerUtils.checkPermission(context, [Permission.camera]);
        if (resultStr == '1') {
          result = await SelectPicUtils.getTakePic(map);
        }
      }
      //照相
    } else if ("1" == type) {
      //选择图片
      result = await SelectPicUtils.getSelectPic(map);

    } else if ("2" == type) {
      var microphoneStatus = await Permission.microphone.request();
      var cameraStatus = await Permission.camera.request();
      var storageStatus = await Permission.storage.request();

// String resultStr = await PerUtils.checkPermission(
//     context, [Permission.speech, Permission.camera, Permission.microphone]);

      if (cameraStatus == PermissionStatus.granted && microphoneStatus == PermissionStatus.granted && storageStatus == PermissionStatus.granted) {
        // 权限被授予，可以拍摄视频
        result = await SelectPicUtils.getSelectVideo(map);
      }else {
        ToastUtils.showToast("请先获取相机/录音等权限");
        return;
      }

    }
    setState(() {
      result.forEach((f) {
        imgs.add(f);
      });
    });



  }

  _bottomView() {
    return Row(
      children: [
        Expanded(
          child: InkWell(
            onTap: () {
              _done();
            },
            child: SafeArea(
              child: Container(
                margin: EdgeInsets.only(left: 15, right: 15),
                height: 45,
                alignment: Alignment.center,
                decoration: BoxDecoration(
                  color: SQColor.theme_color,
                  borderRadius: BorderRadius.circular(10),
                ),
                child: JText('确定', color: Colors.white),
              ),
            ),
          ),
        ),
      ],
    );
  }
  // 提交
  _done() {
    if(_selYhjg == 'reject' && _ysqksmCtr.text.isEmpty) {
      ToastUtils.showToast('请填写验收情况说明');
      return;
    }
    _upLoadImage();
  }

  _upLoadImage() {
    List<String> _uploadimageUrls = [];
    if (_imageUrls.length == 0) {
      _submit([]);
    }else {
      for (int i = 0; i < _imageUrls.length; i++) {
        _uploadimageUrls.add(_imageUrls[i]);
      }

      HttpUtils.httpUpLoadPost(
          HttpBaseConst.serverUrl + HttpBaseConst.UPLOAD, _uploadimageUrls,
              (data) {
            setState(() {
              FileUpLoadBean fileUpLoadBean =
              FileUpLoadBean.fromJson(json.decode(data));
              List filepath = [];
              for (int i = 0; i < fileUpLoadBean.data.length; i++) {
                Map map = {
                  'fileName': fileUpLoadBean.data[i].fileName,
                  'url': fileUpLoadBean.data[i].urlPath,
                };
                filepath.add(map);
              }
              _submit(filepath);
            });
          }, context: context);
    }
  }

  _submit( var acceptanceFileList) {
    var map = {
      'hazardId': StringUtils.getStr(widget.id),
      'acceptanceResultType': _selYhjg,
      'acceptanceFileList': acceptanceFileList,
      'acceptanceDescription': _ysqksmCtr.text,

    };
    ToastUtils.showLoading();
    viewModel.yhys(map);
    viewModel.yhysDataStream().listen((event) {
      ToastUtils.dissLoading();
      if (event['code'] == '0') {
        ToastUtils.showToast('提交成功');
        Navigator.of(context)..pop()..pop();
      } else {
        ToastUtils.showToast(event['msg']);
      }
    }, onError: (e) {
      ToastUtils.dissLoading();
      print(e);
    });
  }

  _commField(
      {bool isMust = false,
      String hintText = '',
      Widget suffixIcon,
      String title = '',
      bool isReadOnly = false,
      int maxLength, bool isEdit = false,//是否可编辑
      var onTap,
      var controller}) {
    return Container(
      margin: EdgeInsets.fromLTRB(15, 15, 15, 0),
      child: Column(
        children: [
          Container(
            child: Row(
              children: [
                isMust
                    ? JText(
                        '* ',
                        color: SQColor.red,
                      )
                    : Container(),
                Container(
                  child: JText(title),
                ),
              ],
            ),
          ),
          Container(
            alignment: Alignment.center,
            margin: EdgeInsets.only(top: 10),
            padding: EdgeInsets.only(
                left: 10,
                right: maxLength == null ? 0 : 10,
                bottom: maxLength == null ? 0 : 10),
            child: TextField(
              controller: controller,
              onTap: onTap,
              maxLength: maxLength,
              readOnly: isReadOnly,
              style: TextStyle(fontSize: Dimens.textSize28),
              decoration: InputDecoration(
                  border: InputBorder.none,
                  hintText: hintText,
                  hintStyle: TextStyle(fontSize: Dimens.textSize28),
                  suffixIcon: suffixIcon),
            ),
            decoration: BoxDecoration(
              color: isEdit ? SQColor.lineE7E7E7 : SQColor.white,
              border: Border.all(
                width: 1,
                color: SQColor.lineE7E7E7,
              ),
              borderRadius: BorderRadius.all(Radius.circular(Dimens.dimens4)),
            ),
          ),
        ],
      ),
    );
  }
}
